"""
Case Type   : 防篡改
Case Name   : 所有对象权限不允许授予PUBLIC
Create At   : 2022/3/7
Owner       : @daiguatutu
Description :
    1.设置参数并重启数据库enableSeparationOfDuty=on
    gs_guc set -N all -I all -c enableSeparationOfDuty=on;
    gs_om -t restart
    2.查询pg_class信息
    select relname,relacl from pg_class where cast(relacl as text)
    like '%,=%}' or cast(relacl as text) like '{=%}';
    3.清理环境
    gs_guc set -N all -I all -c enableSeparationOfDuty=off;
    gs_om -t restart
Expect      :
    1.成功
    2.成功
    3.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node


class Security(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_node = Node('PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.default_value = 'off'

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'enableSeparationOfDuty=on')
        self.assertTrue(mod_msg, '执行失败:' + text)
        result = self.pri_sh.restart_db_cluster()
        self.assertTrue(result, '执行失败' + text)

        text = f'-----step2：查询pg_class信息 expect:成功-----'
        self.log.info(text)
        sql_cmd = "select relname,relacl from pg_class " \
                  "where cast(relacl as text) like '%,=%}}' or " \
                  "cast(relacl as text) like '{{=%}}';"
        self.log.info(sql_cmd)
        msg = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(msg)
        self.assertNotIn('(0 rows)', msg, '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step3：清理环境-----')
        text1 = '-----修改参数enableSeparationOfDuty为初始值并重启数据库 expect:成功-----'
        self.log.info(text1)
        mod_msg1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enableSeparationOfDuty='
                                             f'{self.default_value}')
        restart_res = self.pri_sh.restart_db_cluster()

        self.log.info('-----断言tearDown执行成功-----')
        self.assertTrue(mod_msg1, '执行失败:' + text1)
        self.assertTrue(restart_res, '执行失败:' + text1)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
